{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "fe338f36-682f-4829-b4d5-88f6474ae51f",
   "metadata": {},
   "source": [
    "# 介绍\n",
    "本指南的目的是向你展示如何正确地对 TGI 进行基准测试。如需更多背景信息和解释，请先查看这篇[热门博客](https://huggingface.co/blog/tgi-benchmarking)。\n",
    "\n",
    "## 设置\n",
    "确保你有一个已安装 TGI 的环境；Docker 是一个很好的选择。这里的命令可以很容易地复制/粘贴到终端中，这可能更为便捷。无需强制使用 Jupyter。如果你只是想测试一下，可以复制并使用[derek-thomas/tgi-benchmark-space](https://huggingface.co/spaces/derek-thomas/tgi-benchmark-space)。\n",
    "\n",
    "# TGI 启动器"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "3bbbd715-b424-4863-971f-28119952442e",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "text-generation-launcher 2.2.1-dev0\n"
     ]
    }
   ],
   "source": [
    "!text-generation-launcher --version"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1f860adf-65a1-4ca0-bd94-872c5c8c548b",
   "metadata": {},
   "source": [
    "以下是 TGI 的不同设置选项，请确保通读并决定哪些设置对你的使用场景最为重要。\n",
    "\n",
    "以下是一些最重要的设置：\n",
    "- `--model-id` \n",
    "- `--quantize` 量化可以节省内存，但并不总是能提高速度\n",
    "- `--max-input-tokens` 这可以让 TGI 优化预填充操作\n",
    "- `--max-total-tokens` 与上述设置结合，TGI 现在知道最大输入和输出 token 的限制\n",
    "- `--max-batch-size` 这个设置让 TGI 知道它每次可以处理多少个请求。\n",
    "\n",
    "最后这三个设置共同提供了必要的限制，以便为你的使用场景进行优化。通过合理设置这些选项，你可以显著提高性能。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "8e5b8290-611e-4b27-8c5c-4f5b38a9c5f4",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text Generation Launcher\n",
      "\n",
      "\u001b[1m\u001b[4mUsage:\u001b[0m \u001b[1mtext-generation-launcher\u001b[0m [OPTIONS]\n",
      "\n",
      "\u001b[1m\u001b[4mOptions:\u001b[0m\n",
      "      \u001b[1m--model-id\u001b[0m <MODEL_ID>\n",
      "          The name of the model to load. Can be a MODEL_ID as listed on <https://hf.co/models> like `gpt2` or `OpenAssistant/oasst-sft-1-pythia-12b`. Or it can be a local directory containing the necessary files as saved by `save_pretrained(...)` methods of transformers [env: MODEL_ID=] [default: bigscience/bloom-560m]\n",
      "      \u001b[1m--revision\u001b[0m <REVISION>\n",
      "          The actual revision of the model if you're referring to a model on the hub. You can use a specific commit id or a branch like `refs/pr/2` [env: REVISION=]\n",
      "      \u001b[1m--validation-workers\u001b[0m <VALIDATION_WORKERS>\n",
      "          The number of tokenizer workers used for payload validation and truncation inside the router [env: VALIDATION_WORKERS=] [default: 2]\n",
      "      \u001b[1m--sharded\u001b[0m <SHARDED>\n",
      "          Whether to shard the model across multiple GPUs By default text-generation-inference will use all available GPUs to run the model. Setting it to `false` deactivates `num_shard` [env: SHARDED=] [possible values: true, false]\n",
      "      \u001b[1m--num-shard\u001b[0m <NUM_SHARD>\n",
      "          The number of shards to use if you don't want to use all GPUs on a given machine. You can use `CUDA_VISIBLE_DEVICES=0,1 text-generation-launcher... --num_shard 2` and `CUDA_VISIBLE_DEVICES=2,3 text-generation-launcher... --num_shard 2` to launch 2 copies with 2 shard each on a given machine with 4 GPUs for instance [env: NUM_SHARD=]\n",
      "      \u001b[1m--quantize\u001b[0m <QUANTIZE>\n",
      "          Whether you want the model to be quantized [env: QUANTIZE=] [possible values: awq, eetq, exl2, gptq, marlin, bitsandbytes, bitsandbytes-nf4, bitsandbytes-fp4, fp8]\n",
      "      \u001b[1m--speculate\u001b[0m <SPECULATE>\n",
      "          The number of input_ids to speculate on If using a medusa model, the heads will be picked up automatically Other wise, it will use n-gram speculation which is relatively free in terms of compute, but the speedup heavily depends on the task [env: SPECULATE=]\n",
      "      \u001b[1m--dtype\u001b[0m <DTYPE>\n",
      "          The dtype to be forced upon the model. This option cannot be used with `--quantize` [env: DTYPE=] [possible values: float16, bfloat16]\n",
      "      \u001b[1m--trust-remote-code\u001b[0m\n",
      "          Whether you want to execute hub modelling code. Explicitly passing a `revision` is encouraged when loading a model with custom code to ensure no malicious code has been contributed in a newer revision [env: TRUST_REMOTE_CODE=]\n",
      "      \u001b[1m--max-concurrent-requests\u001b[0m <MAX_CONCURRENT_REQUESTS>\n",
      "          The maximum amount of concurrent requests for this particular deployment. Having a low limit will refuse clients requests instead of having them wait for too long and is usually good to handle backpressure correctly [env: MAX_CONCURRENT_REQUESTS=] [default: 128]\n",
      "      \u001b[1m--max-best-of\u001b[0m <MAX_BEST_OF>\n",
      "          This is the maximum allowed value for clients to set `best_of`. Best of makes `n` generations at the same time, and return the best in terms of overall log probability over the entire generated sequence [env: MAX_BEST_OF=] [default: 2]\n",
      "      \u001b[1m--max-stop-sequences\u001b[0m <MAX_STOP_SEQUENCES>\n",
      "          This is the maximum allowed value for clients to set `stop_sequences`. Stop sequences are used to allow the model to stop on more than just the EOS token, and enable more complex \"prompting\" where users can preprompt the model in a specific way and define their \"own\" stop token aligned with their prompt [env: MAX_STOP_SEQUENCES=] [default: 4]\n",
      "      \u001b[1m--max-top-n-tokens\u001b[0m <MAX_TOP_N_TOKENS>\n",
      "          This is the maximum allowed value for clients to set `top_n_tokens`. `top_n_tokens` is used to return information about the the `n` most likely tokens at each generation step, instead of just the sampled token. This information can be used for downstream tasks like for classification or ranking [env: MAX_TOP_N_TOKENS=] [default: 5]\n",
      "      \u001b[1m--max-input-tokens\u001b[0m <MAX_INPUT_TOKENS>\n",
      "          This is the maximum allowed input length (expressed in number of tokens) for users. The larger this value, the longer prompt users can send which can impact the overall memory required to handle the load. Please note that some models have a finite range of sequence they can handle. Default to min(max_position_embeddings - 1, 4095) [env: MAX_INPUT_TOKENS=]\n",
      "      \u001b[1m--max-input-length\u001b[0m <MAX_INPUT_LENGTH>\n",
      "          Legacy version of [`Args::max_input_tokens`] [env: MAX_INPUT_LENGTH=]\n",
      "      \u001b[1m--max-total-tokens\u001b[0m <MAX_TOTAL_TOKENS>\n",
      "          This is the most important value to set as it defines the \"memory budget\" of running clients requests. Clients will send input sequences and ask to generate `max_new_tokens` on top. with a value of `1512` users can send either a prompt of `1000` and ask for `512` new tokens, or send a prompt of `1` and ask for `1511` max_new_tokens. The larger this value, the larger amount each request will be in your RAM and the less effective batching can be. Default to min(max_position_embeddings, 4096) [env: MAX_TOTAL_TOKENS=]\n",
      "      \u001b[1m--waiting-served-ratio\u001b[0m <WAITING_SERVED_RATIO>\n",
      "          This represents the ratio of waiting queries vs running queries where you want to start considering pausing the running queries to include the waiting ones into the same batch. `waiting_served_ratio=1.2` Means when 12 queries are waiting and there's only 10 queries left in the current batch we check if we can fit those 12 waiting queries into the batching strategy, and if yes, then batching happens delaying the 10 running queries by a `prefill` run [env: WAITING_SERVED_RATIO=] [default: 0.3]\n",
      "      \u001b[1m--max-batch-prefill-tokens\u001b[0m <MAX_BATCH_PREFILL_TOKENS>\n",
      "          Limits the number of tokens for the prefill operation. Since this operation take the most memory and is compute bound, it is interesting to limit the number of requests that can be sent. Default to `max_input_tokens + 50` to give a bit of room [env: MAX_BATCH_PREFILL_TOKENS=]\n",
      "      \u001b[1m--max-batch-total-tokens\u001b[0m <MAX_BATCH_TOTAL_TOKENS>\n",
      "          **IMPORTANT** This is one critical control to allow maximum usage of the available hardware [env: MAX_BATCH_TOTAL_TOKENS=]\n",
      "      \u001b[1m--max-waiting-tokens\u001b[0m <MAX_WAITING_TOKENS>\n",
      "          This setting defines how many tokens can be passed before forcing the waiting queries to be put on the batch (if the size of the batch allows for it). New queries require 1 `prefill` forward, which is different from `decode` and therefore you need to pause the running batch in order to run `prefill` to create the correct values for the waiting queries to be able to join the batch [env: MAX_WAITING_TOKENS=] [default: 20]\n",
      "      \u001b[1m--max-batch-size\u001b[0m <MAX_BATCH_SIZE>\n",
      "          Enforce a maximum number of requests per batch Specific flag for hardware targets that do not support unpadded inference [env: MAX_BATCH_SIZE=]\n",
      "      \u001b[1m--cuda-graphs\u001b[0m <CUDA_GRAPHS>\n",
      "          Specify the batch sizes to compute cuda graphs for. Use \"0\" to disable. Default = \"1,2,4,8,16,32\" [env: CUDA_GRAPHS=]\n",
      "      \u001b[1m--hostname\u001b[0m <HOSTNAME>\n",
      "          The IP address to listen on [env: HOSTNAME=r-derek-thomas-tgi-benchmark-space-geij6846-b385a-lont4] [default: 0.0.0.0]\n",
      "  \u001b[1m-p\u001b[0m, \u001b[1m--port\u001b[0m <PORT>\n",
      "          The port to listen on [env: PORT=80] [default: 3000]\n",
      "      \u001b[1m--shard-uds-path\u001b[0m <SHARD_UDS_PATH>\n",
      "          The name of the socket for gRPC communication between the webserver and the shards [env: SHARD_UDS_PATH=] [default: /tmp/text-generation-server]\n",
      "      \u001b[1m--master-addr\u001b[0m <MASTER_ADDR>\n",
      "          The address the master shard will listen on. (setting used by torch distributed) [env: MASTER_ADDR=] [default: localhost]\n",
      "      \u001b[1m--master-port\u001b[0m <MASTER_PORT>\n",
      "          The address the master port will listen on. (setting used by torch distributed) [env: MASTER_PORT=] [default: 29500]\n",
      "      \u001b[1m--huggingface-hub-cache\u001b[0m <HUGGINGFACE_HUB_CACHE>\n",
      "          The location of the huggingface hub cache. Used to override the location if you want to provide a mounted disk for instance [env: HUGGINGFACE_HUB_CACHE=]\n",
      "      \u001b[1m--weights-cache-override\u001b[0m <WEIGHTS_CACHE_OVERRIDE>\n",
      "          The location of the huggingface hub cache. Used to override the location if you want to provide a mounted disk for instance [env: WEIGHTS_CACHE_OVERRIDE=]\n",
      "      \u001b[1m--disable-custom-kernels\u001b[0m\n",
      "          For some models (like bloom), text-generation-inference implemented custom cuda kernels to speed up inference. Those kernels were only tested on A100. Use this flag to disable them if you're running on different hardware and encounter issues [env: DISABLE_CUSTOM_KERNELS=]\n",
      "      \u001b[1m--cuda-memory-fraction\u001b[0m <CUDA_MEMORY_FRACTION>\n",
      "          Limit the CUDA available memory. The allowed value equals the total visible memory multiplied by cuda-memory-fraction [env: CUDA_MEMORY_FRACTION=] [default: 1.0]\n",
      "      \u001b[1m--rope-scaling\u001b[0m <ROPE_SCALING>\n",
      "          Rope scaling will only be used for RoPE models and allow rescaling the position rotary to accomodate for larger prompts [env: ROPE_SCALING=] [possible values: linear, dynamic]\n",
      "      \u001b[1m--rope-factor\u001b[0m <ROPE_FACTOR>\n",
      "          Rope scaling will only be used for RoPE models See `rope_scaling` [env: ROPE_FACTOR=]\n",
      "      \u001b[1m--json-output\u001b[0m\n",
      "          Outputs the logs in JSON format (useful for telemetry) [env: JSON_OUTPUT=]\n",
      "      \u001b[1m--otlp-endpoint\u001b[0m <OTLP_ENDPOINT>\n",
      "          [env: OTLP_ENDPOINT=]\n",
      "      \u001b[1m--otlp-service-name\u001b[0m <OTLP_SERVICE_NAME>\n",
      "          [env: OTLP_SERVICE_NAME=] [default: text-generation-inference.router]\n",
      "      \u001b[1m--cors-allow-origin\u001b[0m <CORS_ALLOW_ORIGIN>\n",
      "          [env: CORS_ALLOW_ORIGIN=]\n",
      "      \u001b[1m--api-key\u001b[0m <API_KEY>\n",
      "          [env: API_KEY=]\n",
      "      \u001b[1m--watermark-gamma\u001b[0m <WATERMARK_GAMMA>\n",
      "          [env: WATERMARK_GAMMA=]\n",
      "      \u001b[1m--watermark-delta\u001b[0m <WATERMARK_DELTA>\n",
      "          [env: WATERMARK_DELTA=]\n",
      "      \u001b[1m--ngrok\u001b[0m\n",
      "          Enable ngrok tunneling [env: NGROK=]\n",
      "      \u001b[1m--ngrok-authtoken\u001b[0m <NGROK_AUTHTOKEN>\n",
      "          ngrok authentication token [env: NGROK_AUTHTOKEN=]\n",
      "      \u001b[1m--ngrok-edge\u001b[0m <NGROK_EDGE>\n",
      "          ngrok edge [env: NGROK_EDGE=]\n",
      "      \u001b[1m--tokenizer-config-path\u001b[0m <TOKENIZER_CONFIG_PATH>\n",
      "          The path to the tokenizer config file. This path is used to load the tokenizer configuration which may include a `chat_template`. If not provided, the default config will be used from the model hub [env: TOKENIZER_CONFIG_PATH=]\n",
      "      \u001b[1m--disable-grammar-support\u001b[0m\n",
      "          Disable outlines grammar constrained generation. This is a feature that allows you to generate text that follows a specific grammar [env: DISABLE_GRAMMAR_SUPPORT=]\n",
      "  \u001b[1m-e\u001b[0m, \u001b[1m--env\u001b[0m\n",
      "          Display a lot of information about your runtime environment\n",
      "      \u001b[1m--max-client-batch-size\u001b[0m <MAX_CLIENT_BATCH_SIZE>\n",
      "          Control the maximum number of inputs that a client can send in a single request [env: MAX_CLIENT_BATCH_SIZE=] [default: 4]\n",
      "      \u001b[1m--lora-adapters\u001b[0m <LORA_ADAPTERS>\n",
      "          Lora Adapters a list of adapter ids i.e. `repo/adapter1,repo/adapter2` to load during startup that will be available to callers via the `adapter_id` field in a request [env: LORA_ADAPTERS=]\n",
      "      \u001b[1m--usage-stats\u001b[0m <USAGE_STATS>\n",
      "          Control if anonymous usage stats are collected. Options are \"on\", \"off\" and \"no-stack\" Defaul is on [env: USAGE_STATS=] [default: on] [possible values: on, off, no-stack]\n",
      "  \u001b[1m-h\u001b[0m, \u001b[1m--help\u001b[0m\n",
      "          Print help (see more with '--help')\n",
      "  \u001b[1m-V\u001b[0m, \u001b[1m--version\u001b[0m\n",
      "          Print version\n"
     ]
    }
   ],
   "source": [
    "!text-generation-launcher -h"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "af079d13-7f8e-4b3c-bc74-82675ccf84d3",
   "metadata": {},
   "source": [
    "我们可以直接从本指南中启动，因为我们不需要命令是交互式的。\n",
    "\n",
    "在本指南中，我们将使用默认设置，因为目的是理解基准测试工具。\n",
    "\n",
    "如果你在 Space 上运行，以下参数已被更改，因为我们不希望与 Spaces 服务器发生冲突：\n",
    "- `--hostname`\n",
    "- `--port`\n",
    "\n",
    "根据你的需求，你可以随意更改或删除这些参数。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "07778dcf-b5f6-45a7-b76f-e1fc5d3a73a1",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[2m2024-08-16T12:07:56.411768Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Args {\n",
      "    model_id: \"astronomer/Llama-3-8B-Instruct-GPTQ-8-Bit\",\n",
      "    revision: None,\n",
      "    validation_workers: 2,\n",
      "    sharded: None,\n",
      "    num_shard: None,\n",
      "    quantize: Some(\n",
      "        Gptq,\n",
      "    ),\n",
      "    speculate: None,\n",
      "    dtype: None,\n",
      "    trust_remote_code: false,\n",
      "    max_concurrent_requests: 128,\n",
      "    max_best_of: 2,\n",
      "    max_stop_sequences: 4,\n",
      "    max_top_n_tokens: 5,\n",
      "    max_input_tokens: None,\n",
      "    max_input_length: None,\n",
      "    max_total_tokens: None,\n",
      "    waiting_served_ratio: 0.3,\n",
      "    max_batch_prefill_tokens: None,\n",
      "    max_batch_total_tokens: None,\n",
      "    max_waiting_tokens: 20,\n",
      "    max_batch_size: None,\n",
      "    cuda_graphs: None,\n",
      "    hostname: \"0.0.0.0\",\n",
      "    port: 1337,\n",
      "    shard_uds_path: \"/tmp/text-generation-server\",\n",
      "    master_addr: \"localhost\",\n",
      "    master_port: 29500,\n",
      "    huggingface_hub_cache: None,\n",
      "    weights_cache_override: None,\n",
      "    disable_custom_kernels: false,\n",
      "    cuda_memory_fraction: 1.0,\n",
      "    rope_scaling: None,\n",
      "    rope_factor: None,\n",
      "    json_output: false,\n",
      "    otlp_endpoint: None,\n",
      "    otlp_service_name: \"text-generation-inference.router\",\n",
      "    cors_allow_origin: [],\n",
      "    api_key: None,\n",
      "    watermark_gamma: None,\n",
      "    watermark_delta: None,\n",
      "    ngrok: false,\n",
      "    ngrok_authtoken: None,\n",
      "    ngrok_edge: None,\n",
      "    tokenizer_config_path: None,\n",
      "    disable_grammar_support: false,\n",
      "    env: false,\n",
      "    max_client_batch_size: 4,\n",
      "    lora_adapters: None,\n",
      "    usage_stats: On,\n",
      "}\n",
      "\u001b[2m2024-08-16T12:07:56.411941Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mhf_hub\u001b[0m\u001b[2m:\u001b[0m Token file not found \"/data/token\"    \n",
      "\u001b[2Kconfig.json [00:00:00] [████████████████████████] 1021 B/1021 B 50.70 KiB/s (0s)\u001b[2m2024-08-16T12:07:56.458451Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Model supports up to 8192 but tgi will now set its default to 4096 instead. This is to save VRAM by refusing large prompts in order to allow more users on the same hardware. You can increase that size using `--max-batch-prefill-tokens=8242 --max-total-tokens=8192 --max-input-tokens=8191`.\n",
      "\u001b[2m2024-08-16T12:07:56.458473Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Default `max_input_tokens` to 4095\n",
      "\u001b[2m2024-08-16T12:07:56.458480Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Default `max_total_tokens` to 4096\n",
      "\u001b[2m2024-08-16T12:07:56.458487Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Default `max_batch_prefill_tokens` to 4145\n",
      "\u001b[2m2024-08-16T12:07:56.458494Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Using default cuda graphs [1, 2, 4, 8, 16, 32]\n",
      "\u001b[2m2024-08-16T12:07:56.458606Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[1mdownload\u001b[0m: \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Starting check and download process for astronomer/Llama-3-8B-Instruct-GPTQ-8-Bit\n",
      "\u001b[2m2024-08-16T12:07:59.750101Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Download file: model.safetensors\n",
      "^C\n",
      "\u001b[2m2024-08-16T12:08:09.101893Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[1mdownload\u001b[0m: \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Terminating download\n",
      "\u001b[2m2024-08-16T12:08:09.102368Z\u001b[0m \u001b[32m INFO\u001b[0m \u001b[1mdownload\u001b[0m: \u001b[2mtext_generation_launcher\u001b[0m\u001b[2m:\u001b[0m Waiting for download to gracefully shutdown\n"
     ]
    }
   ],
   "source": [
    "!RUST_BACKTRACE=1 \\\n",
    "text-generation-launcher \\\n",
    "--model-id astronomer/Llama-3-8B-Instruct-GPTQ-8-Bit \\\n",
    "--quantize gptq \\\n",
    "--hostname 0.0.0.0 \\\n",
    "--port 1337"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dca32e98-2bd5-45d8-8026-c3620f38ef4d",
   "metadata": {},
   "source": [
    "# TGI 基准测试\n",
    "现在让我们学习如何启动基准测试工具！\n",
    "\n",
    "在这里，我们可以看到 TGI 基准测试的不同设置选项。\n",
    "\n",
    "以下是一些更重要的 TGI 基准测试设置：\n",
    "\n",
    "- `--tokenizer-name` 这是必需的，以便工具知道使用哪个分词器\n",
    "- `--batch-size` 这对于负载测试非常重要。我们应该使用足够的值来查看吞吐量和延迟的变化。请注意，在基准测试工具中，batch-size 是虚拟用户的数量。\n",
    "- `--sequence-length` 也就是输入 tokens，这对于匹配你的使用场景需求非常重要\n",
    "- `--decode-length` 也就是输出 tokens，这对于匹配你的使用场景需求非常重要\n",
    "- `--runs` 默认值是 10\n",
    "\n",
    "<blockquote style=\"border-left: 5px solid #80CBC4; background: #263238; color: #CFD8DC; padding: 0.5em 1em; margin: 1em 0;\">\n",
    "  <strong>💡 提示：</strong> 当你在探索时，使用较小的 <code style=\"background: #37474F; color: #FFFFFF; padding: 2px 4px; border-radius: 4px;\">--runs</code> 值，但在最终确定时使用较高的值，以获得更精确的统计数据。\n",
    "</blockquote>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "2cb3fb6f-d79e-4ce0-ab7c-eb118c088589",
   "metadata": {
    "tags": []
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Text Generation Benchmarking tool\n",
      "\n",
      "\u001b[1m\u001b[4mUsage:\u001b[0m \u001b[1mtext-generation-benchmark\u001b[0m [OPTIONS] \u001b[1m--tokenizer-name\u001b[0m <TOKENIZER_NAME>\n",
      "\n",
      "\u001b[1m\u001b[4mOptions:\u001b[0m\n",
      "  \u001b[1m-t\u001b[0m, \u001b[1m--tokenizer-name\u001b[0m <TOKENIZER_NAME>\n",
      "          The name of the tokenizer (as in model_id on the huggingface hub, or local path) [env: TOKENIZER_NAME=]\n",
      "      \u001b[1m--revision\u001b[0m <REVISION>\n",
      "          The revision to use for the tokenizer if on the hub [env: REVISION=] [default: main]\n",
      "  \u001b[1m-b\u001b[0m, \u001b[1m--batch-size\u001b[0m <BATCH_SIZE>\n",
      "          The various batch sizes to benchmark for, the idea is to get enough batching to start seeing increased latency, this usually means you're moving from memory bound (usual as BS=1) to compute bound, and this is a sweet spot for the maximum batch size for the model under test\n",
      "  \u001b[1m-s\u001b[0m, \u001b[1m--sequence-length\u001b[0m <SEQUENCE_LENGTH>\n",
      "          This is the initial prompt sent to the text-generation-server length in token. Longer prompt will slow down the benchmark. Usually the latency grows somewhat linearly with this for the prefill step [env: SEQUENCE_LENGTH=] [default: 10]\n",
      "  \u001b[1m-d\u001b[0m, \u001b[1m--decode-length\u001b[0m <DECODE_LENGTH>\n",
      "          This is how many tokens will be generated by the server and averaged out to give the `decode` latency. This is the *critical* number you want to optimize for LLM spend most of their time doing decoding [env: DECODE_LENGTH=] [default: 8]\n",
      "  \u001b[1m-r\u001b[0m, \u001b[1m--runs\u001b[0m <RUNS>\n",
      "          How many runs should we average from [env: RUNS=] [default: 10]\n",
      "  \u001b[1m-w\u001b[0m, \u001b[1m--warmups\u001b[0m <WARMUPS>\n",
      "          Number of warmup cycles [env: WARMUPS=] [default: 1]\n",
      "  \u001b[1m-m\u001b[0m, \u001b[1m--master-shard-uds-path\u001b[0m <MASTER_SHARD_UDS_PATH>\n",
      "          The location of the grpc socket. This benchmark tool bypasses the router completely and directly talks to the gRPC processes [env: MASTER_SHARD_UDS_PATH=] [default: /tmp/text-generation-server-0]\n",
      "      \u001b[1m--temperature\u001b[0m <TEMPERATURE>\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: TEMPERATURE=]\n",
      "      \u001b[1m--top-k\u001b[0m <TOP_K>\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: TOP_K=]\n",
      "      \u001b[1m--top-p\u001b[0m <TOP_P>\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: TOP_P=]\n",
      "      \u001b[1m--typical-p\u001b[0m <TYPICAL_P>\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: TYPICAL_P=]\n",
      "      \u001b[1m--repetition-penalty\u001b[0m <REPETITION_PENALTY>\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: REPETITION_PENALTY=]\n",
      "      \u001b[1m--frequency-penalty\u001b[0m <FREQUENCY_PENALTY>\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: FREQUENCY_PENALTY=]\n",
      "      \u001b[1m--watermark\u001b[0m\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: WATERMARK=]\n",
      "      \u001b[1m--do-sample\u001b[0m\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: DO_SAMPLE=]\n",
      "      \u001b[1m--top-n-tokens\u001b[0m <TOP_N_TOKENS>\n",
      "          Generation parameter in case you want to specifically test/debug particular decoding strategies, for full doc refer to the `text-generation-server` [env: TOP_N_TOKENS=]\n",
      "  \u001b[1m-h\u001b[0m, \u001b[1m--help\u001b[0m\n",
      "          Print help (see more with '--help')\n",
      "  \u001b[1m-V\u001b[0m, \u001b[1m--version\u001b[0m\n",
      "          Print version\n"
     ]
    }
   ],
   "source": [
    "!text-generation-benchmark -h"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c786dfa0-e719-45a9-9aa9-e781c3519eba",
   "metadata": {},
   "source": [
    "这是一个示例命令。请注意，我多次添加了感兴趣的 batch sizes，以确保所有的值都能被基准测试工具使用。我还根据预计的用户活动，考虑了哪些 batch sizes 是重要的。\n",
    "\n",
    "<blockquote style=\"border-left: 5px solid #FFAB91; background: #37474F; color: #FFCCBC; padding: 0.5em 1em; margin: 1em 0;\">\n",
    "  <strong>⚠️ 警告：</strong> 请注意，TGI 基准测试工具是设计用来在终端中运行的，而不是在 Jupyter 笔记本中。这意味着你需要将命令复制/粘贴到 Jupyter 终端标签中。我在这里放置它是为了方便。\n",
    "</blockquote>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c4792c04-5a6d-44f1-ad66-3d908b66c8e7",
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "!text-generation-benchmark \\\n",
    "--tokenizer-name astronomer/Llama-3-8B-Instruct-GPTQ-8-Bit \\\n",
    "--sequence-length 70 \\\n",
    "--decode-length 50 \\\n",
    "--batch-size 1 \\\n",
    "--batch-size 2 \\\n",
    "--batch-size 4 \\\n",
    "--batch-size 8 \\\n",
    "--batch-size 16 \\\n",
    "--batch-size 32 \\\n",
    "--batch-size 64 \\\n",
    "--batch-size 128 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ba693082-295b-4505-96de-f68d8f6781e3",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
